import 'package:flutter_demo/core/common/api/home_api.dart';
import 'package:flutter_demo/ui/pages/treasure/module/query_home_page.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';

import 'index.dart';

class TreasureController extends GetxController {
  TreasureController();
  late RefreshController refreshController;
  final state = TreasureState();
  //默认搜索关键词
  final defuleSearch = "你".obs;
  // tap
  void handleTap(int index) {
    Get.snackbar(
      "标题",
      "消息",
    );
  }

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    refreshController = RefreshController();
    super.onInit();
    query(1);
  }

  query(int pageNo) async {
    QueryHomePage value =
        await HomeApi.queryHomePage(pageNo: pageNo.toString());
    //加载中状态
    state.status.value = "1";
    update();
    if (state.vo != null && state.vo?.courseList != null && pageNo != 1) {
      state.vo?.courseList!.addAll(value.courseList!);
    } else {
      state.vo = value;
    }
    //加载完成状态
    state.status.value = "4";
    update();
  }

  //下拉加载更多
  void onMorePage() async {
    await query(state.page + 1);
    state.page += 1;

    if (state.page >= int.parse(state.vo?.totalPage as String)) {
      //最后一页
      refreshController.loadNoData();
    } else {
      refreshController.loadComplete();
    }
  }

  //上拉刷新
  void onRefreshPage() async {
    state.page = 1;
    await query(state.page);
    //去掉刷新按钮和，下拉完成不能重用。 只可用于上拉。
    refreshController.refreshCompleted();

    refreshController.resetNoData();
  }
}
